package cn.aopmin.java.api.lang;

/**
 *线程协作
 * 需求：
 *          1、下载图片
 *          2、打开图片
 * @author 白豆五
 * @since 2025/1/29
 */
public class ThreadJoinTest {

    public static boolean isFinish = false;

    public static void main(String[] args) {

        // 下载图片线程
        Thread download = new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println(Thread.currentThread().getName() + "开始下载图片");
                for (int i = 1; i <= 100; i++) {
                    System.out.println("下载进度：" + i + "%");
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                System.out.println(Thread.currentThread().getName() + "图片下载完毕");
                isFinish = true;
            }
        },"下载图片线程:");

        // 启动下载线程
        download.start();

        //显示图片线程
        Thread showImg = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    download.join();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName() + "准备显示图片");
                try {
                    // 等待下载线程执行完毕，在显示图片
                    download.join();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                if (!isFinish) {
                    throw new RuntimeException("图片下载失败");
                }
                System.out.println(Thread.currentThread().getName() + "显示图片完成");
            }
        },"显示图片线程:");
        // 启动显示图片线程
        showImg.start();
    }
}